/*
 * Copyright (c) 2006-2023, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2023-06-24     RT-Thread    first version
 */

#include <rtthread.h>

#define DBG_TAG "main"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

#include "board.h"
#include "sensor.h"
#include "sensor_dallas_dht11.h"
#include "drv_common.h"

#include <wlan_mgnt.h>
#include <wlan_prot.h>
#include <wlan_cfg.h>


struct dataPoint {

    float dht11_temp;
    float dht11_humi;
    float modbus_air_temp;
    float modbus_air_humi;
    float modbus_wind_speed;
    float modbus_wind_dir;
    float modbus_lightstrength;

}db;

/* Modify this pin according to the actual wiring situation */
#define DHT11_DATA_PIN    GET_PIN(D, 4)

static void get_dht11_sensordata_entry(void *parameter)
{
    rt_device_t dev = RT_NULL;
    struct rt_sensor_data sensor_data;
    rt_size_t res;
    rt_uint8_t get_data_freq = 1; /* 1Hz */

    dev = rt_device_find("temp_dht11");
    if (dev == RT_NULL)
    {
        return;
    }

    if (rt_device_open(dev, RT_DEVICE_FLAG_RDWR) != RT_EOK)
    {
        rt_kprintf("open device failed!\n");
        return;
    }

    rt_device_control(dev, RT_SENSOR_CTRL_SET_ODR, (void *)(&get_data_freq));

    while (1)
    {
        res = rt_device_read(dev, 0, &sensor_data, 1);

        if (res != 1)
        {
            rt_kprintf("read data failed! result is %d\n", res);
            rt_device_close(dev);
            return;
        }
        else
        {
            if (sensor_data.data.temp >= 0)
            {
                uint8_t temp = (sensor_data.data.temp & 0xffff) >> 0;      // get temp
                uint8_t humi = (sensor_data.data.temp & 0xffff0000) >> 16; // get humi
                rt_kprintf("temp:%d, humi:%d\n" ,temp, humi);
                db.dht11_temp = temp;
                db.dht11_humi = humi;
            }
        }

        rt_thread_delay(1000);
    }
}


static int create_dht11_read_thread(void)
{
    rt_thread_t dht11_thrd;

    dht11_thrd = rt_thread_create("get_dht",
                                     get_dht11_sensordata_entry,
                                     RT_NULL,
                                     1024,
                                     RT_THREAD_PRIORITY_MAX / 2,
                                     20);
    if (dht11_thrd != RT_NULL)
    {
        rt_thread_startup(dht11_thrd);
    }

    return RT_EOK;
}

#include "user_mb_app.h"

#define SLAVE_ADDR      MB_SAMPLE_TEST_SLAVE_ADDR
#define PORT_NUM        MB_MASTER_USING_PORT_NUM
#define PORT_BAUDRATE   MB_MASTER_USING_PORT_BAUDRATE
#define PORT_PARITY     MB_PAR_NONE

#define MB_POLL_THREAD_PRIORITY  10
#define MB_SEND_THREAD_PRIORITY  RT_THREAD_PRIORITY_MAX - 1
#define MB_POLL_CYCLE_MS   500

#define AIR_TH_ID                1
#define AIR_WIND_SPEED_ID        2
#define AIR_WIND_DIR_ID          3
#define AIR_LIGHT_STRENGTH_ID    4

extern USHORT   usMRegHoldBuf[MB_MASTER_TOTAL_SLAVE_NUM][M_REG_HOLDING_NREGS];

static void send_thread_entry(void *parameter)
{
    eMBMasterReqErrCode error_code = MB_MRE_NO_ERR;
    rt_uint16_t error_count = 0;

    while (1)
    {
    error_code =  eMBMasterReqReadHoldingRegister(AIR_TH_ID,          /* salve address */
                                                    0,   /* register start address */
                                                    2,     /* register total number */
                                                    RT_WAITING_FOREVER); /* timeout */

    /* Record the number of errors */
    if (error_code != MB_MRE_NO_ERR)
    {
        error_count++;
    }
    rt_thread_mdelay(1000);
    rt_kprintf("temp = %d, humi = %d \r\n",usMRegHoldBuf[AIR_TH_ID-1][1],usMRegHoldBuf[AIR_TH_ID-1][0]);
    db.modbus_air_temp = usMRegHoldBuf[AIR_TH_ID-1][1]*0.1;
    db.modbus_air_humi = usMRegHoldBuf[AIR_TH_ID-1][0]*0.1;


    //-------------风速-----------------
    error_code =  eMBMasterReqReadHoldingRegister(AIR_WIND_SPEED_ID,          /* salve address */
                                                    0,   /* register start address */
                                                    1,     /* register total number */
                                                    RT_WAITING_FOREVER); /* timeout */

    /* Record the number of errors */
    if (error_code != MB_MRE_NO_ERR)
    {
        error_count++;
    }
    rt_thread_mdelay(1000);
    rt_kprintf("wind speed = %d \r\n",usMRegHoldBuf[AIR_WIND_SPEED_ID-1][0]);
    db.modbus_wind_speed = usMRegHoldBuf[AIR_WIND_SPEED_ID-1][0];
    //-------------风向-----------------
    error_code =  eMBMasterReqReadHoldingRegister(AIR_WIND_DIR_ID,          /* salve address */
                                                    1,   /* register start address */
                                                    1,     /* register total number */
                                                    RT_WAITING_FOREVER); /* timeout */

    /* Record the number of errors */
    if (error_code != MB_MRE_NO_ERR)
    {
        error_count++;
    }
    rt_thread_mdelay(1000);
    rt_kprintf("wind dir = %d \r\n",usMRegHoldBuf[AIR_WIND_DIR_ID-1][1]);
    db.modbus_wind_dir = usMRegHoldBuf[AIR_WIND_DIR_ID-1][1];
    //-------------光照-----------------
    error_code =  eMBMasterReqReadHoldingRegister(AIR_LIGHT_STRENGTH_ID,          /* salve address */
                                                    0,   /* register start address */
                                                    2,     /* register total number */
                                                    RT_WAITING_FOREVER); /* timeout */

    /* Record the number of errors */
    if (error_code != MB_MRE_NO_ERR)
    {
        error_count++;
    }
    rt_thread_mdelay(1000);
    rt_kprintf("lightstrength = %d \r\n",usMRegHoldBuf[AIR_LIGHT_STRENGTH_ID-1][1]+usMRegHoldBuf[AIR_LIGHT_STRENGTH_ID-1][0]*0xffff);
    db.modbus_lightstrength = usMRegHoldBuf[AIR_LIGHT_STRENGTH_ID-1][1]+usMRegHoldBuf[AIR_LIGHT_STRENGTH_ID-1][0]*0xffff;           //32位拼接

    }
}




static void mb_master_poll(void *parameter)
{
    eMBMasterInit(MB_RTU, PORT_NUM, PORT_BAUDRATE, PORT_PARITY);
    eMBMasterEnable();

    while (1)
    {
        eMBMasterPoll();
        rt_thread_mdelay(MB_POLL_CYCLE_MS);
    }
}

static int create_modbusRTUsensor_read_thread(void)
{
    static rt_uint8_t is_init = 0;
    rt_thread_t tid1 = RT_NULL, tid2 = RT_NULL;

    if (is_init > 0)
    {
        rt_kprintf("sample is running\n");
        return -RT_ERROR;
    }
    tid1 = rt_thread_create("md_m_poll", mb_master_poll, RT_NULL, 512, MB_POLL_THREAD_PRIORITY, 10);
    if (tid1 != RT_NULL)
    {
        rt_thread_startup(tid1);
    }
    else
    {
        goto __exit;
    }

    tid2 = rt_thread_create("md_m_send", send_thread_entry, RT_NULL, 512, MB_SEND_THREAD_PRIORITY, 10);
    if (tid2 != RT_NULL)
    {
        rt_thread_startup(tid2);
    }
    else
    {
        goto __exit;
    }

    is_init = 1;
    return RT_EOK;

__exit:
    if (tid1)
        rt_thread_delete(tid1);
    if (tid2)
        rt_thread_delete(tid2);

    return -RT_ERROR;
}






#define SSID    "xjaucsandy"
#define PASSWD  "1223334444"

#include "onenet.h"



static void onenet_dataupload_threadEntry(void *parameter)
{

    while (1)
    {
        if (onenet_mqtt_upload_digit("dht11_t", db.dht11_temp) < 0)
        {
            LOG_E("upload has an error, stop uploading");
            break;
        }
        else
        {
            LOG_I("buffer : {\"dht11_t\":%f}", db.dht11_temp);
        }
                rt_thread_delay(rt_tick_from_millisecond(2 * 1000));
        //-------------------------------------------------------

        if (onenet_mqtt_upload_digit("dht11_h", db.dht11_humi) < 0)
        {
            LOG_E("upload has an error, stop uploading");
            break;
        }
        else
        {
            LOG_I("buffer : {\"dht11_h\":%f}", db.dht11_humi);
        }
                rt_thread_delay(rt_tick_from_millisecond(2 * 1000));
        //-------------------------------------------------------
        if (onenet_mqtt_upload_digit("modbus_air_t", db.modbus_air_temp) < 0)
        {
            LOG_E("upload has an error, stop uploading");
            break;
        }
        else
        {
            LOG_I("buffer : {\"modbus_air_t\":%f}", db.modbus_air_temp);
        }
                rt_thread_delay(rt_tick_from_millisecond(2 * 1000));
        //-------------------------------------------------------

        if (onenet_mqtt_upload_digit("modbus_air_h", db.modbus_air_humi) < 0)
        {
            LOG_E("upload has an error, stop uploading");
            break;
        }
        else
        {
            LOG_I("buffer : {\"modbus_air_h\":%f}", db.modbus_air_humi);
        }
        rt_thread_delay(rt_tick_from_millisecond(2 * 1000));
        //-------------------------------------------------------
        if (onenet_mqtt_upload_digit("modbus_wind_speed", db.modbus_wind_speed) < 0)
        {
            LOG_E("upload has an error, stop uploading");
            break;
        }
        else
        {
            LOG_I("buffer : {\"modbus_wind_speed\":%f}", db.modbus_wind_speed);
        }
        rt_thread_delay(rt_tick_from_millisecond(2 * 1000));
        //-------------------------------------------------------
        if (onenet_mqtt_upload_digit("modbus_wind_dir", db.modbus_wind_dir) < 0)
        {
            LOG_E("upload has an error, stop uploading");
            break;
        }
        else
        {
            LOG_I("buffer : {\"modbus_wind_dir\":%f}", db.modbus_wind_dir);
        }
        rt_thread_delay(rt_tick_from_millisecond(2 * 1000));
        //-------------------------------------------------------
        if (onenet_mqtt_upload_digit("modbus_lightstrength", db.modbus_lightstrength) < 0)
        {
            LOG_E("upload has an error, stop uploading");
            break;
        }
        else
        {
            LOG_I("buffer : {\"modbus_lightstrength\":%f}", db.modbus_lightstrength);
        }
        rt_thread_delay(rt_tick_from_millisecond(2 * 1000));
        //-------------------------------------------------------
    }
}

int create_onenet_upload_thread(void)
{
    rt_thread_t tid;
    LOG_I(" STARTT UPLOAD THREAD "  );
    tid = rt_thread_create("onenet_upload",
                           onenet_dataupload_threadEntry,
                           RT_NULL,
                           2 * 1024,
                           RT_THREAD_PRIORITY_MAX / 3 - 1,
                           5);
    if (tid)
    {
        rt_thread_startup(tid);
    }

    return 0;
}

int main(void)
{

//    LOG_D("Hello RT-Thread!");
    //--------connect AP--------
    while(RT_EOK != rt_wlan_connect(SSID,PASSWD)){
        rt_thread_mdelay(3000);
        LOG_E("WIFI connect failed, please check AP name and password, try to connect again......");
    }

   create_dht11_read_thread();
   create_modbusRTUsensor_read_thread();

    onenet_mqtt_init();
    rt_thread_mdelay(5000);                 // 注意：连接完onenet broker后，确保延时一段时间后，再上报数据，否则线程会阻塞
    create_onenet_upload_thread();



//   while(1){
////    LOG_D("DHT11_T=%f,DHT11_H=%f,AIR_T=%f,AIR_H=%f,WIND_SPD=%f,WIND_DIR=%f,LIGHT_STRTH=%f",
////            db.dht11_temp,db.dht11_humi,db.modbus_air_temp,db.modbus_air_humi,db.modbus_wind_speed,db.modbus_wind_dir,db.modbus_lightstrength);
//    rt_thread_delay(1000);
//
//   }

    return RT_EOK;
}
